package com.course02.order_backend.security.LXY;


import com.course02.order_backend.entity.LXY.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 封装用户信息user(UserDetails)
 * @author wozhe
 */
@Data
public class LoginUserDetails implements UserDetails {
    private User user;
    //获取角色名字和权限名字
    private List<String> roleCodes;
    private List<String> permissionCodes;
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

    public LoginUserDetails(User user, List<String> roleCodes, List<String> permissionCodes) {
        this.user = user;
        this.roleCodes = roleCodes;
        this.permissionCodes = permissionCodes;
    }
    /**
     *当前账号的权限，不能为null，可以为空
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        //不是空就添加角色ROLE_和权限
        if(!CollectionUtils.isEmpty(roleCodes)){
            //将角色设置到GrantedAuthority中，官网要求角色要加上前缀 ROLE_xxx 区分其它权限
            for (String roleCode  : roleCodes) {
                if (StringUtils.hasText(roleCode)) {
                    authorities.add(new SimpleGrantedAuthority(roleCode.trim()));
                }
            }
        }
        //不是空就添加权限
        if(!CollectionUtils.isEmpty(permissionCodes)){
            //将权限设置到GrantedAuthority中
            for (String permissionCode : permissionCodes) {
                if (StringUtils.hasText(permissionCode)) {
                    authorities.add(new SimpleGrantedAuthority(permissionCode.trim()));
                }
            }
        }
        return authorities;
    }

    /**
     * 获取密码
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     */
    @Override
    public String getUsername() {
        return user.getPhone();
    }

    /**
     * 账号是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
//        return UserDetails.super.isAccountNonExpired();
    }

    /**
     * 是否被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
//        return UserDetails.super.isAccountNonLocked();
    }

    /**
     * 密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
//        return UserDetails.super.isCredentialsNonExpired();
    }

    /**
     * 账户是否有效
     */
    @Override
    public boolean isEnabled() {
        return true;
//        return UserDetails.super.isEnabled();
    }
}
